package com.awise.app.timer.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;

import com.awise.R;
import com.awise.base.BaseActivity;
import com.awise.http.RoverGlobal;
import com.awise.util.Utils;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;

import java.util.ArrayList;

/**
 * Created by lihaifeng on 2018/1/24.
 */

public class TimerAddOrEditActivity extends BaseActivity {

    private TextView mTvTime;
    private RadioButton mBtnGradient;
    private RadioButton mBtnJumping;
    private RadioGroup mGroupEffect;
    private ImageView mBack;
    private TextView mTvBrightness1;
    private VerticalSeekBar mSeekbar1;
    private TextView mTvBrightness2;
    private VerticalSeekBar mSeekbar2;
    private TextView mTvBrightness3;
    private VerticalSeekBar mSeekbar3;
    private TextView mTvBrightness4;
    private VerticalSeekBar mSeekbar4;
    private TextView mTvBrightness5;
    private VerticalSeekBar mSeekbar5;
    private ChartView mChartView;
    private TimePicker mTimePicker;

    private ArrayList<FrameData> frameDataList;
    private byte[] time;

    private FrameData currentFrameData;
    private int brightnessCount;

    private static final String TAG = "TimerAddOrEditActivity";

    private int value1;
    private int value2;
    private int value3;
    private int value4;
    private int value5;

    private Handler handler = new Handler();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_add_or_edit_layout);
        initData();
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startTimerMode();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                sendTimeModeCommand((byte)value1, (byte)value2, (byte)value3, (byte)value4, (byte)value5);
            }
        }, 150);
    }

    @Override
    protected void onStop() {
        super.onStop();
        finishTimeMode();
    }

    private void initData() {
        brightnessCount = getSP(this,"ControlNumber", 5);
        Bundle bundle = getIntent().getExtras();
        frameDataList = bundle.getParcelableArrayList("data");
        time = bundle.getByteArray("time");
        for(int i=0; i<frameDataList.size(); i++) {
            FrameData data = frameDataList.get(i);
            byte[] tempTime = data.getTime();
            if(time[0] == tempTime[0] && time[1] == tempTime[1]) {
                currentFrameData = data;
                break;
            }
        }
        if(currentFrameData == null) {
            currentFrameData = new FrameData();
            currentFrameData.setTime(time);
            byte[] brightnesses = new byte[5];
            for(int i = 0; i<brightnessCount; i++) {
                brightnesses[i] = 0x64;
            }
            currentFrameData.setBrightnesses(brightnesses);
            currentFrameData.setEffect((byte)0x00);
            int index = -1;
            for (int i = 0; i < frameDataList.size(); i++) {
                byte[] time1 = frameDataList.get(i).getTime();
                byte[] time2 = null;
                if (i + 1 < frameDataList.size()) {
                    time2 = frameDataList.get(i + 1).getTime();
                }
                if (time2 != null && (time1[0] * 60 + time1[1]) <= (time[0] * 60 + time[1])
                        && (time[0] * 60 + time[1]) <= (time2[0] * 60 + time2[1])) {
                    index = i + 1;
                }
            }
            if(index != -1) {
                frameDataList.add(index, currentFrameData);
            }
        }
    }

    private void initView() {
        mTvTime = (TextView) findViewById(R.id.tv_time);
        mBtnGradient = (RadioButton) findViewById(R.id.btn_gradient);
        mBtnJumping = (RadioButton) findViewById(R.id.btn_jumping);
        mGroupEffect = (RadioGroup) findViewById(R.id.group_effect);
        mBack = (ImageView) findViewById(R.id.back);
        View brightnessLayout1 = findViewById(R.id.layout_brightness1);
        mTvBrightness1 = (TextView) brightnessLayout1.findViewById(R.id.tv_brightness1);
        mSeekbar1 = (VerticalSeekBar) brightnessLayout1.findViewById(R.id.seekbar1);
        View brightnessLayout2 = findViewById(R.id.layout_brightness2);
        mTvBrightness2 = (TextView) brightnessLayout2.findViewById(R.id.tv_brightness1);
        mSeekbar2 = (VerticalSeekBar) brightnessLayout2.findViewById(R.id.seekbar1);
        View brightnessLayout3 = findViewById(R.id.layout_brightness3);
        mTvBrightness3 = (TextView) brightnessLayout3.findViewById(R.id.tv_brightness1);
        mSeekbar3 = (VerticalSeekBar) brightnessLayout3.findViewById(R.id.seekbar1);
        View brightnessLayout4 = findViewById(R.id.layout_brightness4);
        mTvBrightness4 = (TextView) brightnessLayout4.findViewById(R.id.tv_brightness1);
        mSeekbar4 = (VerticalSeekBar) brightnessLayout4.findViewById(R.id.seekbar1);
        View brightnessLayout5 = findViewById(R.id.layout_brightness5);
        mTvBrightness5 = (TextView) brightnessLayout5.findViewById(R.id.tv_brightness1);
        mSeekbar5 = (VerticalSeekBar) brightnessLayout5.findViewById(R.id.seekbar1);
        mChartView = (ChartView) findViewById(R.id.chartview);
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);

        switch (brightnessCount) {
            case 1:
                brightnessLayout1.setVisibility(View.VISIBLE);
                brightnessLayout2.setVisibility(View.GONE);
                brightnessLayout3.setVisibility(View.GONE);
                brightnessLayout4.setVisibility(View.GONE);
                brightnessLayout5.setVisibility(View.GONE);
                break;
            case 2:
                brightnessLayout1.setVisibility(View.VISIBLE);
                brightnessLayout2.setVisibility(View.VISIBLE);
                brightnessLayout3.setVisibility(View.GONE);
                brightnessLayout4.setVisibility(View.GONE);
                brightnessLayout5.setVisibility(View.GONE);
                break;
            case 3:
                brightnessLayout1.setVisibility(View.VISIBLE);
                brightnessLayout2.setVisibility(View.VISIBLE);
                brightnessLayout3.setVisibility(View.VISIBLE);
                brightnessLayout4.setVisibility(View.GONE);
                brightnessLayout5.setVisibility(View.GONE);
                break;
            case 4:
                brightnessLayout1.setVisibility(View.VISIBLE);
                brightnessLayout2.setVisibility(View.VISIBLE);
                brightnessLayout3.setVisibility(View.VISIBLE);
                brightnessLayout4.setVisibility(View.VISIBLE);
                brightnessLayout5.setVisibility(View.GONE);
                break;
            case 5:
                brightnessLayout1.setVisibility(View.VISIBLE);
                brightnessLayout2.setVisibility(View.VISIBLE);
                brightnessLayout3.setVisibility(View.VISIBLE);
                brightnessLayout4.setVisibility(View.VISIBLE);
                brightnessLayout5.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("data", frameDataList);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        mSeekbar1.setOnSeekBarChangeListener(new TimerEditOnSeekBarChangeListener(0));
        mSeekbar2.setOnSeekBarChangeListener(new TimerEditOnSeekBarChangeListener(1));
        mSeekbar3.setOnSeekBarChangeListener(new TimerEditOnSeekBarChangeListener(2));
        mSeekbar4.setOnSeekBarChangeListener(new TimerEditOnSeekBarChangeListener(3));
        mSeekbar5.setOnSeekBarChangeListener(new TimerEditOnSeekBarChangeListener(4));

        mGroupEffect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.btn_gradient) {
                    currentFrameData.setEffect((byte)0x00);
                } else {
                    currentFrameData.setEffect((byte)0x01);
                }
                mChartView.setFrames(frameDataList);
            }
        });

        mChartView.setPeriodType(0);
        mChartView.setBrightnessCount(brightnessCount);
        mChartView.setTopBrightnessViewAndVisibility(false);
        mChartView.setVerticalLineVisibility(false);
        mChartView.setFrames(frameDataList);

        byte[] time = currentFrameData.getTime();
        mTvTime.setText(String.format(getResources().getString(R.string.current_time_point_and_effect), Utils.formatTime(time)));
        mTimePicker.setIs24HourView(true);
        mTimePicker.setCurrentHour((int)time[0]);
        mTimePicker.setCurrentMinute((int)time[1]);
        mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                byte[] tempTime = currentFrameData.getTime();
                tempTime[0] = (byte)hourOfDay;
                tempTime[1] = (byte)minute;
                currentFrameData.setTime(tempTime);
                sort(frameDataList);
                mChartView.setFrames(frameDataList);
                mTvTime.setText(String.format(getResources().getString(R.string.current_time_point_and_effect), Utils.formatTime(tempTime)));
            }
        });

        byte effect = currentFrameData.getEffect();
        if(effect == 0x00) {
            mBtnGradient.setChecked(true);
        } else {
            mBtnJumping.setChecked(true);
        }

        byte[] brigresses = currentFrameData.getBrightnesses();
        value1 = brigresses[0];
        value2 = brigresses[1];
        value3 = brigresses[2];
        value4 = brigresses[3];
        value5 = brigresses[4];

        mSeekbar1.setProgress(value1);
        mSeekbar2.setProgress(value2);
        mSeekbar3.setProgress(value3);
        mSeekbar4.setProgress(value4);
        mSeekbar5.setProgress(value5);


    }

    private void updateBrightness(int index, int progress) {
        byte[] brightnesses = currentFrameData.getBrightnesses();
        brightnesses[index] = (byte)progress;
        currentFrameData.setBrightnesses(brightnesses);
        mChartView.setFrames(frameDataList);

        sendTimeModeCommand((byte)value1, (byte)value2, (byte)value3, (byte)value4, (byte)value5);
    }

    private void sort(ArrayList<FrameData> list) {
        for(int i=0; i<list.size(); i++) {
            for(int j=0; j<list.size()-i; j++) {
                if(j + 1 < list.size() -i) {
                    byte[] time1 = list.get(j).getTime();
                    byte[] time2 = list.get(j+1).getTime();
                    if(time1[0] * 60 + time1[1] > time2[0] * 60 + time2[1]) {
                        FrameData temp = list.get(j);
                        list.set(j, list.get(j+1));
                        list.set(j+1, temp);
                    }
                }

            }
        }
    }

    /**
     * 进入定时模式
     */
    public void startTimerMode() {
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x26, 0x00, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length - 1);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    /**
     * 发送定时模式指令
     * @param value1
     * @param value2
     * @param value3
     * @param value4
     * @param value5
     */
    public void sendTimeModeCommand(byte value1, byte value2, byte value3, byte value4, byte value5) {
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x3c, 0x00, 0x00, 0x05, value1, value2, value3, value4, value5, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length - 1);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    /**
     * 结束定时模式
     */
    public void finishTimeMode() {
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x28, 0x00, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length - 1);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    public class TimerEditOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        int index = -1;
        public TimerEditOnSeekBarChangeListener(int index) {
            this.index = index;
        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            switch (index) {
                case 0:
                    value1 = mSeekbar1.getProgress();
                    mTvBrightness1.setText(value1 + "%");
                    updateBrightness(0, value1);
                    break;
                case 1:
                    value2 = mSeekbar2.getProgress();
                    mTvBrightness2.setText(value2 + "%");
                    updateBrightness(1, value2);
                    break;
                case 2:
                    value3 = mSeekbar3.getProgress();
                    mTvBrightness3.setText(value3 + "%");
                    updateBrightness(2, value3);
                    break;
                case 3:
                    value4 = mSeekbar4.getProgress();
                    mTvBrightness4.setText(value4 + "%");
                    updateBrightness(3, value4);
                    break;
                case 4:
                    value5 = mSeekbar5.getProgress();
                    mTvBrightness5.setText(value5 + "%");
                    updateBrightness(4, value5);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            sendTimeModeCommand((byte)value1, (byte)value2, (byte)value3, (byte)value4, (byte)value5);
        }
    }
}
